package com.voicechat.firstmet.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mabeijianxi.jianxiexpression.widget.ExpressionEditText;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.adapter.CommentAdapter;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.CommentBean;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.client.OssClient;
import com.voicechat.firstmet.client.OssConfig;
import com.voicechat.firstmet.fragment.EmojiShowFragment;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.CommunityService;
import com.voicechat.firstmet.utils.GlideLoadUtils;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.utils.Utils;
import com.voicechat.firstmet.view.CircleImageView;
import com.voicechat.firstmet.view.EmojiKeyboard;
import com.voicechat.firstmet.view.EmotionInputDetector;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity_imessage
 * @ClassName: CommentDetailsActivity
 * @Description: 评论详情页面
 * @Author: ljp
 * @CreateDate: 2018/10/31 16:16
 * @Version: 1.0
 */
public class CommentDetailsActivity extends BaseActivity {
    @BindView(R.id.recycler_comment)
    RecyclerView recyclerComment;
    @BindView(R.id.linear_back)
    LinearLayout linearBack;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smartRefresh;
    @BindView(R.id.et_comment_content)
    ExpressionEditText etCommentContent;
    @BindView(R.id.tv_like_num)
    TextView tvLikeNum;
    @BindView(R.id.image_enjoy)
    ImageView imageEnjoy;
    @BindView(R.id.image_share)
    ImageView imageShare;
    @BindView(R.id.fl_emogi)
    FrameLayout flEmogi;
    @BindView(R.id.image_like)
    ImageView imageLike;
    @BindView(R.id.linear_zan)
    LinearLayout linearZan;
    @BindView(R.id.tv_send)
    TextView tvSend;

    private CommentBean.PageBean.ListBean listBean;
    private MySelfInfoBean.ObjectBean mySeleInfo;
    private String userId;
    private String token;
    int page = 1;
    private String deviceInfo;
    private EmojiShowFragment emojiShowFragment;
    private EmojiKeyboard emojiKeyboard;
    private CommentAdapter commentAdapter;
    private ArrayList<CommentBean.PageBean.ListBean> commentBeans;
    private EmotionInputDetector mDetector;
    private String TAG = "CommentDetailsActivity";

    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_comment_details;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        //透明状态栏
        StatusBarUtils.Full(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        listBean = getIntent().getParcelableExtra("listBean");
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        userId = mySeleInfo.getId();
        token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        deviceInfo = PhoneUtils.getDeviceInfo(context);
        initView();
        initKeyBoard();
        initHttpComment();
    }

    /**
     * @return
     * @method
     * @description 控件数据实例化
     * @date: 2018/11/1 16:05
     * @author: ljp
     */
    private void initView() {
        EmojiShowFragment.setEditMsg(etCommentContent);
        tvLikeNum.setText(listBean.getFabulousCount() + "");
        if (listBean.getIsFabulous().equals("1")) {//我是否点赞  0 未点赞  1 已经点赞
            imageLike.setImageResource(R.mipmap.post_detail_like);
        } else {
            imageLike.setImageResource(R.mipmap.post_detail_unlike);
        }
        etCommentContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                /*判断是否是“GO”键*/
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    /*隐藏软键盘*/
                    Utils.hideSoftInput(v.getWindowToken(),activity);
                        initHttpSeccondCommentData();//二级评论请求
                    return true;
                }
                return false;
            }
        });
        etCommentContent.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    linearZan.setVisibility(View.GONE);
                    imageShare.setVisibility(View.GONE);
                    tvSend.setVisibility(View.VISIBLE);
                }else {
                    linearZan.setVisibility(View.VISIBLE);
                    imageShare.setVisibility(View.VISIBLE);
                    tvSend.setVisibility(View.GONE);
                }

            }
        });
        tvSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*隐藏软键盘*/
                Utils.hideSoftInput(v.getWindowToken(),activity);
                    initHttpSeccondCommentData();//二级评论请求
            }
        });
        //点赞，取消赞
        imageLike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommunityService.postLikeAndUnLike(token, deviceInfo, listBean.getId(),
                        CommunityService.LIKE_TYPE.LIKE_POST_TYPE, userId).subscribe(result -> {
                    if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                        if (!TextUtils.isEmpty(listBean.getIsFabulous()) && listBean.getIsFabulous().equals("0")) {// 1 已经点赞   0 未点赞
                            listBean.setIsFabulous("1");
                            listBean.setFabulousCount(listBean.getFabulousCount() + 1);
                            tvLikeNum.setText(listBean.getFabulousCount() + "");
                            imageLike.setImageResource(R.mipmap.post_detail_like);
                        } else if (!TextUtils.isEmpty(listBean.getIsFabulous()) && listBean.getIsFabulous().equals("1")) {
                            listBean.setIsFabulous("0");
                            listBean.setFabulousCount(listBean.getFabulousCount() - 1);
                            imageLike.setImageResource(R.mipmap.post_detail_unlike);
                            tvLikeNum.setText(listBean.getFabulousCount() + "");
                        }
                    } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_FAIL) {
                        toast_MakeText(result.getMsg());
                    }
                }, throwable -> {
                    //Log.i(TAG, "setLikeClick: -------" + throwable.toString());
                });
            }
        });
        commentBeans = new ArrayList<>();
        //下拉刷新
        smartRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                initHttpComment();
                smartRefresh.finishRefresh(10000);
            }
        });
        //上拉加载更多
        smartRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                initHttpComment();
                smartRefresh.finishLoadMore(10000);
            }
        });
        //设置 Header 为 贝塞尔雷达 样式
        smartRefresh.setRefreshHeader(new ClassicsHeader(context));
        smartRefresh.setRefreshFooter(new ClassicsFooter(context));
        commentAdapter = new CommentAdapter(context, commentBeans, R.layout.item_comment, listBean);
        commentAdapter.addHeaderView(R.layout.item_comment_head);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
        //linearLayoutManager.setReverseLayout(true);
        // linearLayoutManager.setStackFromEnd(true);
        recyclerComment.setLayoutManager(linearLayoutManager);
        recyclerComment.setAdapter(commentAdapter);
        commentAdapter.setItemClick(new CommentAdapter.ItemClick() {
            @Override
            public void setLikeClick(View view, CommentBean.PageBean.ListBean listBean) {
                CommunityService.postLikeAndUnLike(token, deviceInfo, listBean.getId(),
                        CommunityService.LIKE_TYPE.LIKE_POST_TYPE, userId).subscribe(result -> {
                    if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                        if (!TextUtils.isEmpty(listBean.getIsFabulous()) && listBean.getIsFabulous().equals("0")) {// 1 已经点赞   0 未点赞
                            listBean.setIsFabulous("1");
                            listBean.setFabulousCount(listBean.getFabulousCount() + 1);
                            tvLikeNum.setText(listBean.getFabulousCount() + "");
                            imageLike.setImageResource(R.mipmap.post_detail_like);
                        } else if (!TextUtils.isEmpty(listBean.getIsFabulous()) && listBean.getIsFabulous().equals("1")) {
                            listBean.setIsFabulous("0");
                            listBean.setFabulousCount(listBean.getFabulousCount() - 1);
                            imageLike.setImageResource(R.mipmap.post_detail_unlike);
                            tvLikeNum.setText(listBean.getFabulousCount() + "");
                        }
                    } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_FAIL) {
                        toast_MakeText(result.getMsg());
                    }
                }, throwable -> {
                    //Log.i(TAG, "setLikeClick: -------" + throwable.toString());
                });
            }
        });
    }
    /**
     * @return
     * @method
     * @description 回复别人的评论
     * @date: 2018/11/2 15:55
     * @author: ljp
     */
    private void initHttpSeccondCommentData() {
            String content = etCommentContent.getText().toString().trim();
            if(!TextUtils.isEmpty(content)) {
                CommunityService.submitPostComment2(token, deviceInfo, listBean.getId(), userId, content).subscribe(result -> {
                    Log.i(TAG, "initHttpCommentData: -------" + result.toString());
                    if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                        page = 1;
                        initHttpComment();
                        etCommentContent.setText("");
                    }else if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                        Utils.setToken(context);
                    }else {
                        toast_MakeText(result.getMsg());
                    }
                }, throwable -> {
                    Log.i(TAG, "initHttpCommentData: -------" + throwable.toString());

                });
            }else {
                toast_MakeText("请输入评论内容");
            }
    }

    /**
     * @return
     * @method
     * @description 2级评论数据
     * @date: 2018/11/1 14:12
     * @author: ljp
     */
    private void initHttpComment() {
        CommunityService.postCommentTwo(token, deviceInfo, listBean.getId(), userId, page + "").subscribe(commentBean -> {
            if (commentBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                int i = commentBean.getPage().getCount() / commentBean.getPage().getPageSize() +
                        (commentBean.getPage().getCount() % commentBean.getPage().getPageSize() == 0 ? 0 : 1);
                if (page > i) {//判断是否是最后一页{//判断是否是最后一页
                    smartRefresh.finishLoadMoreWithNoMoreData();//完成加载并标记没有更多数据 1.0.4
                } else {
                    if (page == 1) {
                        commentBeans.clear();
                        smartRefresh.finishRefresh();
                    }
                    commentBeans.addAll(commentBean.getPage().getList());
                    commentAdapter.notifyDataSetChanged();
                    smartRefresh.finishLoadMore();
                }
            }else if(commentBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                removeAllActivity();
                startActivity(new Intent(activity,LoginActivity.class));
            }else {
                toast_MakeText(commentBean.getMsg());
            }
        }, throwable -> {

        });
    }

    private void initKeyBoard() {
        if (emojiShowFragment == null) {
            emojiShowFragment = EmojiShowFragment.newInstance();
            getSupportFragmentManager().beginTransaction().replace(R.id.fl_emogi, EmojiShowFragment.newInstance()).commit();
        }
        emojiKeyboard = new EmojiKeyboard(this, etCommentContent, flEmogi, imageEnjoy, smartRefresh);
        emojiKeyboard.setEmoticonPanelVisibilityChangeListener(new EmojiKeyboard.OnEmojiPanelVisibilityChangeListener() {
            @Override
            public void onShowEmojiPanel() {
                //Log.e(TAG, "onShowEmojiPanel");
            }

            @Override
            public void onHideEmojiPanel() {
                // Log.e(TAG, "onHideEmojiPanel");
            }
        });
       /* mDetector = EmotionInputDetector.with(this)
               // .bindSendButton(mSendButton)
                .bindToEditText(null,etCommentContent)
                .setEmotionView(flEmogi)
                .bindToContent(smartRefresh)
                .bindToEmotionButton(imageEnjoy);*/
    }

    @OnClick({R.id.linear_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.linear_back:
                finish();
                break;

        }
    }
}
